package com.msb.servicemap.service.impl;

import com.msb.commons.constant.AmapConstant;
import com.msb.commons.constant.CommonStatusEnum;
import com.msb.commons.dto.DicDistrict;
import com.msb.commons.response.ResponseResult;
import com.msb.servicemap.mapper.DicDistrictMapper;
import com.msb.servicemap.service.DicDistrictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chshh
 * @since 2022-10-25
 */
@Service
public class DicDistrictServiceImpl extends ServiceImpl<DicDistrictMapper, DicDistrict> implements DicDistrictService {
    @Value("${amap.key}")
    private String amapKey;

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private DicDistrictMapper dicDistrictMapper;

    @Override
    public ResponseResult initDistrict(String keywords) {
        //接口地址
        //https://restapi.amap.com/v3/config/district?keywords=%E5%8C%97%E4%BA%AC&subdistrict=3&key=0e18e92d4fd4b3d09eb13666c11b8004
        //拼装请求的url
        StringBuilder url = new StringBuilder();

        url.append(AmapConstant.DISTRICT_URL);
        url.append("?");
        url.append("keywords=" + keywords);
        url.append("&");
        url.append("subdistrict=3");
        url.append("&");
        url.append("key=" + amapKey);
        System.out.println(url.toString());
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url.toString(), String.class);
        String body = forEntity.getBody();

        //解析结果
        JSONObject entityJsonObject = JSONObject.fromObject(body);
        //根据status判断是否成功
        int status = entityJsonObject.getInt(AmapConstant.STATUS);
        if (status != 1) {
            return ResponseResult.fail(CommonStatusEnum.MAP_DISTRICT_ERROR.getCode(), CommonStatusEnum.MAP_DISTRICT_ERROR.getValue());
        }

        JSONArray countryJsonArray = entityJsonObject.getJSONArray(AmapConstant.DISTRICTS);
        for (int i = 0; i < countryJsonArray.size(); i++) {
            JSONObject districtJsonObject = countryJsonArray.getJSONObject(i);
            String addressCode = getDicDistrict(districtJsonObject, "0");

            JSONArray provinceJsonArray = districtJsonObject.getJSONArray(AmapConstant.DISTRICTS);
            for (int j = 0; j < provinceJsonArray.size(); j++) {
                JSONObject provinceJsonObject = provinceJsonArray.getJSONObject(j);
                String provinceAddressCode = getDicDistrict(provinceJsonObject, addressCode);

                JSONArray cityJsonArray = provinceJsonObject.getJSONArray(AmapConstant.DISTRICTS);
                for (int p = 0; p < cityJsonArray.size(); p++) {
                    JSONObject cityJsonObject = cityJsonArray.getJSONObject(p);
                    String cityAddressCode = getDicDistrict(cityJsonObject, provinceAddressCode);

                    JSONArray districtJsonArray = cityJsonObject.getJSONArray(AmapConstant.DISTRICTS);
                    for (int z = 0; z < districtJsonArray.size(); z++) {
                        JSONObject jsonObject = districtJsonArray.getJSONObject(z);

                        //不记录街道
                        String levelString = jsonObject.getString(AmapConstant.LEVEL);
                        if (levelString.equals(AmapConstant.STREET)) {
                            continue;
                        }
                        getDicDistrict(jsonObject, cityAddressCode);
                    }
                }
            }
        }
        return ResponseResult.success();
    }

    /**
     * 传入Json对象，提取数据库对象并且插入数据库
     * @param jSONObject
     * @param parentAddressCode
     * @return 返回addressCode，做为下一级的parentAddressCode
     */
    public String getDicDistrict(JSONObject jSONObject,String parentAddressCode){

        String addressCode = jSONObject.getString(AmapConstant.ADCODE);
        String addressName = jSONObject.getString(AmapConstant.NAME);
        String levelString = jSONObject.getString(AmapConstant.LEVEL);
        int level = getLevel(levelString);
        insertDicDistrict(addressCode, addressName, parentAddressCode, level);

        return addressCode;
    }

    /**
     * 提取数据库对象并且插入数据库
     * @param addressCode
     * @param addressName
     * @param parentAddressCode
     * @param level
     */
    public void insertDicDistrict(String addressCode,String addressName,String parentAddressCode,Integer level){

        DicDistrict dicDistrict = new DicDistrict();
        dicDistrict.setAddressCode(addressCode);
        dicDistrict.setAddressName(addressName);
        dicDistrict.setParentAddressCode(parentAddressCode);
        dicDistrict.setLevel(level);
        dicDistrictMapper.insert(dicDistrict);
    }

    /**
     * 使level改为0.1.2.3级别
     * @param levelString
     * @return
     */
    public int getLevel(String levelString){
        int level = 0;

        if (levelString.trim().equals("country")){
            level = 0;
        }else if (levelString.trim().equals("province")){
            level = 1;
        }else if (levelString.trim().equals("city")){
            level = 2;
        }else if (levelString.trim().equals("district")){
            level = 3;
        }
        return level;
    }

}
